# -*- coding: utf-8 -*-

import redis

from contract_market import settings

redis__version__ = "redis version : {}".format(redis.__version__)
print(redis__version__.center(20, "*"))


class OPRedis:
    """
    redis operator
    """
    POOLNAME = "pool"

    def __init__(self, pool=None, db=None) -> None:
        """ """
        if not hasattr(self, self.POOLNAME):
            self.pool = pool or OPRedis.get_redis_conn(db)
        self._cursor = redis.Redis(
            connection_pool=self.pool, max_connections=10)

    @classmethod
    def get_redis_conn(cls, db=None):
        """ pool """
        return redis.ConnectionPool(
            host=settings.REDIS_HOST,
            password=settings.REDIS_PASSWORD,
            port=settings.REDIS_PORT,
            db=db or settings.REDIS_DB
        )

    def new(self, *,
            host=settings.REDIS_HOST,
            port: int = settings.REDIS_PORT,
            password: str = settings.REDIS_PASSWORD,
            db: int = settings.REDIS_DB):
        """
        Reconstruct the instance,  
        For example, when DB needs different libraries, 
        it can create instances without instantiating the class multiple times,  
        The instance can be rebuilt using built-in methods 
        """
        host = host if host else self.host
        self.pool = redis.ConnectionPool(
            host=host,
            password=password,
            port=port,
            db=db
        )
        self.__init__()

    @classmethod
    def init(cls, *,
             host=settings.REDIS_HOST,
             port: int = settings.REDIS_PORT,
             password: str = settings.REDIS_PASSWORD,
             db: int = settings.REDIS_DB
             ):
        pool = redis.ConnectionPool(
            host=host,
            password=password,
            port=port,
            db=db
        )
        return cls(pool)

    def __getattr__(self, name):
        """ proxy """
        if name == self.POOLNAME:
            return super().__getattr__(name)
        return getattr(self._cursor, name)
